#include <TFile.h>
#include <TTree.h>
#include <string>
#include <iostream>
#include <TH1D.h>
#include <TCanvas.h>
// #include "setup.h"
using namespace std;

string HomeDir = "/media/wlf/Data_6_T/wlf/HIRIBL-TOF/HIRFTOF/";
void DifferenceOfCoarse()
{
    const int MaxSig = 10000;

    TFile *file = new TFile((HomeDir + "RootData/Pair_Run_DAS2_data1_20250714T222403_0.root").c_str(), "read");
    TTree *treeSort;
    file->GetObject("treePair", treeSort);
    long long coarse[MaxSig], tsslc;
    short brd, ch[MaxSig];
    int nSig;
    // treeSort->Draw("coarse:tsSlc>>hpid", "", "colz");
    // c1->Draw();
    treeSort->SetBranchAddress("coarse", coarse);
    treeSort->SetBranchAddress("tsSlc", &tsslc);
    treeSort->SetBranchAddress("brd", &brd);
    treeSort->SetBranchAddress("nSig", &nSig);

    int Entries = treeSort->GetEntries();
    TH1D *hDiffCoarseCh = new TH1D("hDiffCoarseCh", "Difference of Coarse", 200000, 1, 1000);
    TH1D *hDiffCoarseiBd = new TH1D("hDiffCoarseiBd", "Difference of Coarse", 200000, -10000, 10000);
    double diffCoarseCh, diffCoarseBrd;
    cout << "Entries: " << Entries << endl;
    TCanvas *c1 = new TCanvas("c1", "c1", 800, 600);
    for (int iEvt = 0; iEvt < Entries - 1; iEvt++)
    {
        treeSort->GetEntry(iEvt);
        double tsSlc1 = tsslc;
        double Brd1 = brd;
        long long Coarse1 = coarse[0];

        treeSort->GetEntry(iEvt + 1);
        double tsSlc2 = tsslc;
        double Brd2 = brd;
        long long Coarse2 = coarse[0];

        if (tsSlc1 == tsSlc2 && Brd1 != Brd2 && nSig != 0)
            hDiffCoarseiBd->Fill(Coarse1 - Coarse2);
        iEvt++;
    }
    hDiffCoarseiBd->Draw();
    c1->SetLogy();
    c1->Draw();
}